package com.tingyuge.thinking.spring.validation;

import com.tingyuge.thinking.spring.ioc.overview.domain.User;
import org.springframework.context.MessageSource;
import org.springframework.validation.*;

import java.util.Locale;

import static com.tingyuge.thinking.spring.validation.ErrorsMessageDemo.createMessageSource;

/**
 * @author xiaodao
 * @version 1.0
 * @date 2021/12/12
 * @description
 * @see Validator
 */
public class ValidatorDemo {

    public static void main(String[] args) {
        Validator validator = new UserValidator();

        //2.判断是否支持目标对象
        User user = new User();
        System.out.println("user 对象是否 被 userValidator支持 : "+ validator.supports(user.getClass()));
        Errors errors = new BeanPropertyBindingResult(user, "user");
        validator.validate(user, errors);
        MessageSource messageSource = createMessageSource();
        for (ObjectError allError : errors.getAllErrors()) {
            String message = messageSource.getMessage(allError.getCode(), allError.getArguments(), Locale.getDefault());
            System.out.println(message);
        }
    }

    static class UserValidator implements Validator{
        @Override
        public boolean supports(Class<?> clazz) {
            return User.class.isAssignableFrom(clazz);
        }

        @Override
        public void validate(Object target, Errors errors) {
            User user = (User) target;
            ValidationUtils.rejectIfEmptyOrWhitespace(errors,"id","id.required");
            ValidationUtils.rejectIfEmptyOrWhitespace(errors,"name","name.required");
        }
    }
}
